<?php
//=======================================
//###################################
// Kayako Web Solutions
//
// Source Copyright 2001-2004 Kayako Web Solutions
// Unauthorized reproduction is not allowed
// License Number: $%LICENSE%$
// $Author: vshoor $ ($Date: 2006/04/11 20:58:15 $)
// $RCSfile: functions_importexport.php,v $ : $Revision: 1.6 $ 
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
//
//###################################
//=======================================

if (!defined("INSWIFT")) {
	trigger_error("Unable to process $PHP_SELF", E_USER_ERROR);
}

/**
* Imports the knowledgebase data from the given file
*/
function importKBData($filename)
{
	global $_SWIFT, $xml, $dbCore, $datastore;

	// Parse the Knowledgebase XML File.
	$xmldata = $xml->xml2tree(implode("", file($filename)));
	$ft = &$xmldata["knowledgebase"][0]["children"];

	$usergroupidlist = $_catpointer = $_articlepointer = $_linkpointer = $linksql = $linklist = $_rccatlist = array();

	// Get the User Group list, we assign it to all users
	$dbCore->query("SELECT `usergroupid` FROM `". TABLE_PREFIX ."usergroups` ORDER BY `usergroupid` ASC;");
	while ($dbCore->nextRecord())
	{
		$usergroupidlist[] = $dbCore->Record["usergroupid"];
	}

	// First lets process all the categories and insert em
	for ($ii=0; $ii<count($ft["category"]); $ii++)
	{
		$category = &$ft["category"][$ii]["children"];
		$kbcategoryid = $category["kbcategoryid"][0]["values"][0];
		$parentcategoryid = $category["parentcategoryid"][0]["values"][0];
		$title = $category["title"][0]["values"][0];
		$categorytype = $category["categorytype"][0]["values"][0];
		$displayorder = $category["displayorder"][0]["values"][0];
		if (!empty($_catpointer[$parentcategoryid])) {
			$newparentcategoryid = $_catpointer[$parentcategoryid];
		} else {
			$newparentcategoryid = 0;
		}
		
		$newkbcategoryid = insertKnowledgebaseCategory($newparentcategoryid, $title, $displayorder, $categorytype, $usergroupidlist);
		$_rccatlist[] = $newkbcategoryid;
		$_catpointer[$kbcategoryid] = $newkbcategoryid;
	}

	// Now we process the articles
	for ($ii=0; $ii<count($ft["article"]); $ii++)
	{
		$article = &$ft["article"][$ii]["children"];
		$kbarticleid = $article["kbarticleid"][0]["values"][0];
		$subject = $article["subject"][0]["values"][0];
		$displayorder = $article["displayorder"][0]["values"][0];
		$articlestatus = $article["articlestatus"][0]["values"][0];
		$contents = $article["contents"][0]["values"][0];

		$newkbarticleid = insertKBArticle($subject, $articlestatus, $displayorder, array(), $contents);
		$_articlepointer[$kbarticleid] = $newkbarticleid;
	}

	// Now we hop onto the links
	for ($ii=0; $ii<count($ft["link"]); $ii++)
	{
		$link = &$ft["link"][$ii]["children"];
		$kbarticleid = $link["kbarticleid"][0]["values"][0];
		$kbcategoryid = $link["kbcategoryid"][0]["values"][0];

		if (!empty($_articlepointer[$kbarticleid]))
		{
			$newkbarticleid = $_articlepointer[$kbarticleid];
			if (!empty($_catpointer[$kbcategoryid]))
			{
				$newkbcategoryid = $_catpointer[$kbcategoryid];
			} else {
				// Add to Parent Category
				$newkbcategoryid = 0;
			}

			$linklist[$newkbarticleid][] = $newkbcategoryid;
		}
	}

	foreach ($linklist as $key=>$val)
	{
		updateArticleLinks($key, $val);
	}

	if (count($_rccatlist))
	{
		recountKBCategory($_rccatlist);
	}

	return true;
}

/**
* Export all the given Knowledgebase Categories
*/
function exportKBCategories($kbcategoryidlist)
{
	global $dbCore, $_SWIFT, $xml;

	if (!_is_array($kbcategoryidlist))
	{
		return false;
	}

	// Fetch all the categories and their child categories first
	$kbcategoryidchildlist = $kbcategorydata = $kbarticledata = $kblinkdata = $kbarticleidlist = array();
	foreach ($kbcategoryidlist as $key=>$val)
	{
		$kbcategoryidchildlist[] = $val;
		if ($val != 0)
		{
			$kbcategoryidchildlist = array_merge($kbcategoryidchildlist, fetchChildCategories($val, ($_temp = array())));
		}
	}

	// Now that we have all the categories, build the query list for it
	$kbcategoryquerylist = buildIN($kbcategoryidchildlist);

	// Ok, great.. now we fetch all the categories
	$dbCore->query("SELECT * FROM `". TABLE_PREFIX ."kbcategories` WHERE `kbcategoryid` IN (". $kbcategoryquerylist .") ORDER BY `kbcategoryid` ASC;");
	while ($dbCore->nextRecord())
	{
		$kbcategorydata[$dbCore->Record["kbcategoryid"]] = $dbCore->Record;
	}

	// Fetch all the links
	$dbCore->query("SELECT * FROM `". TABLE_PREFIX ."kbarticlelinks` WHERE `kbcategoryid` IN (". $kbcategoryquerylist .") ORDER BY `kbarticlelinkid` ASC;");
	while ($dbCore->nextRecord())
	{
		$kblinkdata[$dbCore->Record["kbarticlelinkid"]] = $dbCore->Record;
		if (!in_array($dbCore->Record["kbarticleid"], $kbarticleidlist))
		{
			$kbarticleidlist[] = $dbCore->Record["kbarticleid"];
		}
	}

	// Now.. We fetch all articles
	$dbCore->query("SELECT * FROM `". TABLE_PREFIX ."kbarticles` AS kbarticles LEFT JOIN `". TABLE_PREFIX ."kbarticledata` AS kbarticledata ON (kbarticles.kbarticleid = kbarticledata.kbarticleid) WHERE kbarticles.kbarticleid IN (". buildIN($kbarticleidlist) .") ORDER BY kbarticles.kbarticleid ASC;");
	while ($dbCore->nextRecord())
	{
		$kbarticledata[$dbCore->Record["kbarticleid"]] = $dbCore->Record;
	}

	$xml->addComment(sprintf($_SWIFT["language"]["generationdate"], edate($_SWIFT["settings"]["dt_datetimeformat"], DATENOW)));
	$xml->addParentTag("knowledgebase");
	
	// Build the category XML
	$xml->addComment($_SWIFT["language"]["xmlcatstart"]);
	foreach ($kbcategorydata as $key=>$val)
	{
		$xml->addParentTag("category");
		$xml->addTag("kbcategoryid", $val["kbcategoryid"]);
		$xml->addTag("parentcategoryid", $val["parentcategoryid"]);
		$xml->addTag("title", $val["title"]);
		$xml->addTag("categorytype", $val["categorytype"]);
		$xml->addTag("displayorder", $val["displayorder"]);
		$xml->endParentTag("category");
	}
	$xml->addComment($_SWIFT["language"]["xmlcatend"]);

	// Build the Article XML
	$xml->addComment($_SWIFT["language"]["xmlarticlestart"]);
	foreach ($kbarticledata as $key=>$val)
	{
		$xml->addParentTag("article");
		$xml->addTag("kbarticleid", $val["kbarticleid"]);
		$xml->addTag("subject", $val["subject"]);
		$xml->addTag("displayorder", $val["displayorder"]);
		$xml->addTag("articlestatus", $val["articlestatus"]);
		$xml->addTag("contents", $val["contents"]);
		$xml->endParentTag("article");
	}
	$xml->addComment($_SWIFT["language"]["xmlarticleend"]);

	// Super.. now we do the links
	$xml->addComment($_SWIFT["language"]["xmllinkstart"]);
	foreach ($kblinkdata as $key=>$val)
	{
		$xml->addParentTag("link");
		$xml->addTag("kbcategoryid", $val["kbcategoryid"]);
		$xml->addTag("kbarticleid", $val["kbarticleid"]);
		$xml->endParentTag("link");
	}
	$xml->addComment($_SWIFT["language"]["xmllinkend"]);

	$xml->endParentTag("knowledgebase");

	$xmldata = $xml->returnXML();


	$filename = "knowledgebase.xml";

	if(isset($_SERVER['HTTP_USER_AGENT']) && preg_match("/MSIE/", $_SERVER['HTTP_USER_AGENT'])) {
		// IE Bug in download name workaround
		ini_set( 'zlib.output_compression','Off' );
	}

	header("Content-Type: application/force-download");

	if (strpos($_SERVER['HTTP_USER_AGENT'], "MSIE")){
		header("Content-Disposition: attachment; filename=\"". $filename ."\"");
	} else{
		header("Content-Disposition: attachment; filename=\"". $filename ."\"");
	}

	header("Content-Transfer-Encoding: binary");
	header("Content-Length: ". strlen($xmldata));

	echo $xmldata;

	return true;
}
?>